<?php
namespace app\Home\controller;

// 引入底层控制器
use app\common\controller\Home;

// 继承底层控制器
class Index extends Home
{   public $NoLogin = ["*"];
    public function __construct(){
        
        // 继承底层的构造函数
        parent::__construct();

        // 在公共区域中加载模型，下面的方法都可以用
        $this->BusinessModel = model('Business.User');
        $this->SubjectModel = model('Subject.Subject');
        $this->ChapterModel = model('Subject.Chapter');
        $this->CommentModel = model('Subject.Comment');
        $this->OrderModel = model('Subject.Order');
    }

    // 首页
    public function index()
    {
        $top = $this->SubjectModel->order("createtime desc")->limit(5)->select();
        // var_dump($top);
        // exit;
        $list = $this->SubjectModel->order("id desc")->limit(8)->select();
        // var_dump($list);
        // exit;
        $data = [
            'top' => $top,
            'list' => $list
        ];
        $this->assign($data);
        // 渲染一个页面模板
        return $this->view->fetch();
    }

    // 注册
    public function register(){
        // 判断是否是post请求
        if($this->request->isPost()){
            // 接收手机号和密码
            $mobile = $this->request->param('mobile','','trim');
            $password = $this->request->param('password','','trim');
            // var_dump($mobile,$password);
            // exit;

            // 判断密码是否为空
            if(empty($password)){
                $this->error("密码不能为空");
                exit;
            } 

            // 获取密码盐
            $salt = randstr();
            // var_dump($salt);
            // exit;
            // 密码加密
            $password = md5($password.$salt);

            // 查询出云课堂的渠道来源的id信息 数据库查询

            // 查询整条数据
            // $source = model('common/Business/Source')->where(['name'=>['LIKE',"%云课堂%"]])->find();

            $data = [
                'mobile' => $mobile,
                'nickname' => $mobile,
                'password' => $password,
                'salt' => $salt,
                'gender' => '0', //性别
                'deal' => '0', //成交状态
                'money' => '0',//余额
                'auth' => '0' //实名认证
            ];

             // 查询一个字段
             $data['sourceid'] = model('common/Business/Source')->where(['name'=>['LIKE',"%云课堂%"]])->value('id');

             // var_dump($sourceid);
             // exit;

            // var_dump($data);
            // exit;

            // 执行插入，返回自增的条数
            $result = $this->BusinessModel->validate('common/Business/Business')->save($data); 
            
            if($result === FALSE){
                // 失败
                $this->error($this->BusinessModel->getError());
                exit;
            }else{
                $this->success('注册成功',url('home/index/login'));
                exit;
            }
        }
        // 访问地址www.fast.com/index.php/home/index/register
        // 渲染地址 application/home/view/index/register.html
        return $this->view->fetch();
    }

    // 登录
    public function login(){
        // 判断是否为post请求
        if($this->request->isPost()){
            $mobile = $this->request->param('mobile','','trim');
            $password = $this->request->param('password','','trim');
            // var_dump($mobile,$password);
            // exit;

            $user =$this->BusinessModel->where(['mobile'=>$mobile])->find();
            // var_dump($source->toArray());
            // exit;
            if(!$user){
                $this->error("手机号未注册，请注册后登录");
            }

            $salt = $user->salt;
            if(md5($password.$salt) != $user['password']){
                $this->error("密码错误，登录失败");
            }
            
            // 保存cookie信息
            $cookie = [
                'id' => $user['id'],
                'mobile' => $user['mobile']
            ];

            // 存放cookie 关闭浏览器之后自动销毁
            cookie('business',$cookie);

            $this->success("登录成功",url('home/business/index'));
            exit;
            
        }


        // 访问地址 www.fast.com/index.php/home/index/login
        // 渲染地址 application/home/view/index/login.html
        return $this->view->fetch();
    }

    // 搜索
    public function search(){
        // 先判断是否有ajax请求过来
        if($this->request->isAjax()){
            $page = $this->request->param('page',1,'trim');
            $limit = $this->request->param('limit',10,'trim');
            $search = $this->request->param('search','','trim');
            // var_dump($page,$limit,$search);
            // exit;
            $where = [];

            if(!empty($search)){
                // 模糊查询
                $where['title'] = ['LIKE',"%$search%"];
            }

            // 查询数据总数
            $count = $this->SubjectModel->where($where)->count();
            // var_dump($count);
            // exit;
            // 偏移量
            $start = ($page-1)*$limit;
            $list = $this->SubjectModel
            ->with(['category'])
            ->where($where)
            ->order('createtime desc')
            ->limit($start, $limit)
            ->select();
            
            $data = [
                'count' => $count,
                'list' => $list
            ];

            // 打印
            // var_dump(collection($list)->toArray());
            // exit;

            if(empty($list)){
                $this->error('暂无更多数据');
                exit;
            }else{
                $this->success('成功返回数据',null,$data);
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 退出登录
    public function logout(){
        // 清除cookie
        cookie('business',null);
        $this->success('退出登录',url('home/index/login'));
        exit;
    }

    // 详情页
    public function info(){
        $pid = $this->request->param('pid',0,'trim');
        // var_dump($pid);
        // exit;

        // 找到对应的课程
        $subject = $this->SubjectModel->find($pid);
       
        if(!$subject){
            $this->error('课程不存在',url('home/index/search'));
            exit;
        }

        // 课程章节
        $chapter = $this->ChapterModel->where(['subid'=>$pid])->select();
        // var_dump($chapter);
        // exit;

        // 评论
        $comment = $this->CommentModel->with(['business'])->where(['subid'=>$pid])->limit(8)->select();
        // var_dump($comment);
        // exit;

        // 判断是否登录,不跳转
        $business = $this->auth(false);
        
        if($business){
            $busid = $business['id'];
            $likes = $subject['likes'];

            // 将点赞人的id 转换成数组
            if(empty($likes)){
                $likes = [];
            }else{
                $likes = explode(",",$likes);
            }

            // var_dump($likes);
            // exit;
            // 判断当前登录的人是否在数组中
            if(in_array($busid,$likes)){
                $subject['like_status'] = true;
            }else{
                $subject['like_status'] = false;
            }
        }else{
            //没有登录
            $subject['like_status'] = false;
        }

        // var_dump($subject['like_status']);
        // exit;

        $data = [
            'subject' => $subject,
            'chapter' => $chapter,
            'comment' => $comment
        ];
        $this->assign($data);

        return $this->view->fetch();
    }

    // 点赞
    public function like(){
        if($this->request->isAjax()){
            // var_dump(123);
            // exit;
            $subid = $this->request->param('subid',0,'trim');
            $status = $this->request->param('status','','trim');

            if(!in_array($status,['add','remove'])){
                $this->error('点赞状态有问题');
                exit;
            }

            // 判断是否登录
            $business = $this->auth(false);

            if(!$business){
                $this->error('请登录');
                exit;
            }

            // 判断课程是否存在
            $subject = $this->SubjectModel->where(['id'=>$subid])->find();

            if(!$subject){
                $this->error('课程不存在');
                exit;
            }

            $likes = empty($subject['likes']) ? [] : explode(',',$subject['likes']);

            // 如果在点赞列表内，就取消点赞，如果不在就添加进去
            if(in_array($business['id'],$likes)){
                $pos = array_search($business['id'],$likes);

                // 移出去
                unset($likes[$pos]);
            }else{
                $likes[] = $business['id'];
            }


            // 怕遗漏 去重
            $likes = array_unique($likes);

            $likes = implode(",",$likes);

            // 组装数据
            $data = [
                'id' => $subid,
                'likes' => $likes
            ];

            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if($result === FALSE){
                $msg = $status == "remove" ? '点赞失败' : '取消点赞失败';
                $this->error($msg);
                exit;
            }else{
                $msg = $status == "add" ? '点赞成功': '取消点赞成功';
                $this->success($msg);
                exit;
            }
        }
    }

    // 显示更多评论
    public function comment_list(){
        $subid = $this->request->param('subid',0,'trim');
        // var_dump($subid);
        // exit;
        $subject = $this->SubjectModel->find($subid);
        $data = [
            'subject' => $subject
        ];
        $this->assign($data);
        // var_dump($subject);
        // exit;
        if($this->request->isAjax()){
            $page = $this->request->param('page',0,'trim');
            $limit = $this->request->param('limit',10,'trim');
            // var_dump($page,$limit);
            // exit;
            $subid = $this->request->param('subid',0,'trim');

            $count = $this->CommentModel->where(['subid'=>$subid])->count();
            // $count = count(collection($comment)->toArray());
            // var_dump($count);
            // exit;

            if(!$count){
                $this->error('暂无更多评论',url('home/index/info'));
                exit;
            }

            // 偏移量
            $start = ($page-1)*$limit;
            $list = $this->CommentModel
            ->with(['business'])
            ->where('subid',$subid)
            ->order('createtime desc')
            ->limit($start, $limit)
            ->select();
            
            $data = [
                'count' => $count,
                'list' => $list
            ];

            // var_dump($data);
            // exit;
            if(empty($list)){
                $this->error('暂无更多评论');
                exit;
            }else{
                $this->success('成功返回评论',null,$data);
                exit;
            }
            

        }

        return $this->view->fetch();
    }

    // 购买
    public function buy(){
        if($this->request->isAjax()){
            $subid = $this->request->param('subid',0,'trim');
            // var_dump($subid);
            // exit;

            // 判断课程是否存在
            $subject = $this->SubjectModel->find($subid);
            // var_dump($subject);
            // exit;
            if(empty($subject)){
                $this->error('课程不存在');
                exit;
            }

            // 判断是否登录
            $business = $this->auth(false);
            // var_dump($business);
            // exit;
            if(empty($business)){
                $this->error('请先登录');
                exit;
            }

            // 先判断用户是否购买该课程
            $where = [
                'busid' => $business['id'],
                'subid' => $subid
            ];

            $order = $this->OrderModel->where($where)->find();

            if($order){
                $this->error('您已购买该课程');
                exit;
            }

            // 课程订单插入
            // 用户 余额更新
            // 用户消费记录 插入

            // 加载模型
            $OrderModel = model('Subject.Order');
            $BusinessModel = model('Business.User');
            $RecordModel = model('Business.Record');

            // 开启事务
            $OrderModel->startTrans();
            $BusinessModel->startTrans();
            $RecordModel->startTrans();

            // 判断用户是否余额充足
            $money = empty($business['money']) ? 0 : $business['money'];
            $price = empty($subject['price']) ? -1 : $subject['price'];

            if($price < 0){
                $this->error("课程的价格有误，无法购买");
                exit;
            }

            // 两个高精度数相减
            $UpdateMoney = bcsub($money,$price,2);

            // 用户余额不足
            if($UpdateMoney < 0){
                $this->error('您的余额不足，请充值');
                exit;
            }

            // 生成订单号
            $code = build_code('SUB');

            // 组装订单数据
            $OrderData = [
                'subid' => $subid,
                'busid' => $business['id'],
                'total' => $price,
                'code' => $code
            ];

            // 执行插入
            $OrderStatus = $OrderModel->validate('common/Subject/Order')->save($OrderData);

            if($OrderData === FALSE){
                $this->error($OrderModel->getError());
                exit;
            }

            // 更新用户余额表
            $BusinessData = [
                'id' => $business['id'],
                'money' => $UpdateMoney
            ];

            // 验证器
            $validate = [
                [
                  'money' => 'require|number|>=:0'  
                ],
                [
                    'money.require' => '余额未知',
                    'money.number' => '余额必须是数字',
                    'money.>=' => '余额必须大于等于0'
                ]
            ];
            
            // 执行更新
            $BusinessStatus = $BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if($BusinessStatus === FALSE){
                $OrderModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            $title = $subject['title'];
            $content = "您购买了课程【{$title}】:花费了：￥ $price 元";

            // 插入消费记录
            $RecordData = [
                'total' => -$price,
                'busid' => $business['id'],
                'content' => $content
            ];

            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

            if($RecordStatus === FALSE){
                $BusinessModel->rollback();
                $OrderModel->rollback();
                $this->error($RecordModel->getError());
                exit;
            }

            // 总的判断
            if($OrderStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE){
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $OrderModel->rollback();
                $this->error('购买课程失败');
                exit;
            }
            else{
                // 提交事务
                $OrderModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();

                $this->success('购买课程成功');
                exit;
            }
        }
    }

    // 播放视频
    public function play(){
        $subid = $this->request->param('subid',0,'trim');
        $cid = $this->request->param('cid',0,'trim');
        // var_dump($subid,$cid);
        // exit;

        if(!$subid){
            $this->error('课程不存在');
            exit;
        }

        // 判断章节是否存在
        $chapter = $this->ChapterModel->find($cid);
        // var_dump($chapter);
        // exit;

        if(!$chapter){
            // 根据cid查找该课程的第一个章节
            $chapter = $this->ChapterModel->where(['subid'=>$subid])->order('id asc')->find();
            
            if(!$chapter){
                $this->error('该课程没有章节');
                exit;
            }
        }

        // 是否登录
        $business = $this->auth(false);

        if(!$business){
            $this->error('请先登录');
            exit;
        }

        // 去查询用户是否购买了该课程
        $where = [
            'busid' => $business['id'],
            'subid' => $subid
        ];

        $order = $this->OrderModel->where($where)->find();
        // 如果订单不存在，则用户没有购买
        if(!$order){
            $this->success('请先购买课程',null,['status'=>'buy']);
            exit;
        }else{
            $this->success('已购买',null,$chapter);
        }

    }
}
